package com.jplus.core.plugin.aspect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

import com.jplus.core.utill.Assert;
import com.jplus.core.utill.clazz.ClassUtil;

public class ExecutionKit {

	// execution(<返回类型模式>空格<包名.类名.方法名模式>(<参数N模式>))

	public static boolean analysis(Method method, Aspect aspect) {

		// 1.判断注解
		Class<?> declarClazz = method.getDeclaringClass();
		if (aspect.anno().length > 0) {
			for (Class<? extends Annotation> ans : aspect.anno()) {
				if (ClassUtil.hasAnnotation(declarClazz, ans))
					return true;
			}
		}
		// 2.判断表达式
		if (aspect.value().length > 0) {
			String[] regexs = aspect.value();
			for (String regex : regexs) {
				Assert.notNull(regex, "The regex is not correct, please check:" + regex);
				if (checkRegex(method, regex))
					return true;
			}
		}
		return false;

	}

	/**
	 * @TODO 需要优化
	 */
	private static boolean checkRegex(Method method, String regex) {
		Expression exp1 = new Expression(method);
		Expression exp2 = new Expression(regex);
		boolean bo = Pattern.matches(exp2.getExpression(), exp1.getExpression());
		return bo;
	}
}
